package com.example.chunqiubackend.controller;

import com.example.chunqiubackend.pojo.Result;
import com.example.chunqiubackend.pojo.User;
import com.example.chunqiubackend.service.UserService;
import com.example.chunqiubackend.utils.JwtUtil;
import com.example.chunqiubackend.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    //登录
    @PostMapping("/login")
    public Result login(String email,String passwd) {
        User user = userService.findByEmail(email);
        if (Md5Util.getMD5String(passwd).equals(user.getPasswd())){
            //成功
            Map<String, Object> claims = new HashMap<>();
            claims.put("email", email);
            String jwt = JwtUtil.genToken(claims);
            return Result.success(jwt);
        }else
            return Result.error("账号或密码错误");
    }

    //注册
    @PostMapping("/register")
    public Result register(String email,String passwd){
        User user = userService.findByEmail(email);
        if (user != null)
            return Result.error("邮箱已存在");

        String pattern = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
        if (!email.matches( pattern))
            return Result.error("账号必须为邮箱格式");

        String md5Passwd = Md5Util.getMD5String(passwd);
        userService.register(email,md5Passwd,LocalDateTime.now(),LocalDateTime.now());
        return Result.success("注册成功");
    }

    //修改密码
    @PostMapping("/uppasswd")
    public Result updatePasswd(String email,String old_passwd,String new_passwd){
        if (email==null || old_passwd==null || new_passwd==null|| email.equals("")|| old_passwd.equals("")|| new_passwd.equals(""))
            return Result.error("缺少参数");

        User user = userService.findByEmail(email);
        String old_md5Passwd = Md5Util.getMD5String(old_passwd);
        if (user == null)
            return Result.error("用户不存在");
        if (!old_md5Passwd.equals(user.getPasswd()))
            return Result.error("原密码错误");

        String new_md5Passwd = Md5Util.getMD5String(new_passwd);
        userService.uppasswd(email,new_md5Passwd,LocalDateTime.now());
        return Result.success("修改成功");
    }

}
